package com.ruoyi.materials.service.impl;

import java.util.Date;
import java.util.List;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.materials.domain.LwMaterial;
import com.ruoyi.materials.domain.LwMaterialInfo;
import com.ruoyi.materials.mapper.LwMaterialInfoMapper;
import com.ruoyi.materials.mapper.LwMaterialMapper;
import com.ruoyi.sfproduct.domain.vo.MaterialVo;
import lombok.extern.slf4j.Slf4j;
import lombok.extern.slf4j.XSlf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.materials.mapper.LwOrderMapper;
import com.ruoyi.materials.domain.LwOrder;
import com.ruoyi.materials.service.ILwOrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import java.text.SimpleDateFormat;
import java.util.Locale;

/**
 * 原材料订单Service业务层处理
 * 
 * @author sl
 * @date 2023-12-10
 */
@Slf4j
@Service
public class LwOrderServiceImpl implements ILwOrderService 
{
    @Autowired
    private LwOrderMapper lwOrderMapper;

    @Autowired
    private LwMaterialInfoMapper lwMaterialInfoMapper;

    @Autowired
    private LwMaterialMapper lwMaterialMapper;

    // 创建 SimpleDateFormat 对象，指定中文时间格式
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss", Locale.CHINESE);

    /**
     * 查询原材料订单
     * 
     * @param orderId 原材料订单主键
     * @return 原材料订单
     */
    @Override
    public LwOrder selectLwOrderByOrderId(Long orderId)
    {
        return lwOrderMapper.selectLwOrderByOrderId(orderId);
    }

    /**
     * 查询原材料订单列表
     * 
     * @param lwOrder 原材料订单
     * @return 原材料订单
     */
    @Override
//    public List<LwOrder> selectLwOrderList(LwOrder lwOrder) {
//        PageUtils.clearPage();
//// 查询所有material，数量少于5000的物料
//        List<LwMaterial> materialNumbers = lwMaterialMapper.selectLwMaterialListAndquantityDemand(5000);
//        List<LwOrder> lwOrderList = lwOrderMapper.selectLwOrderList(lwOrder);
//        // 设置所有订单状态为1
//        lwOrderList.forEach(order -> {
//            order.setStatus(1L);
//            lwOrderMapper.updateLwOrder(order);
//        });
//
//// 遍历订单列表，如果订单中的materialNumber在需求物料列表中，则将订单状态设置为2
//        lwOrderList.forEach(order -> {
//            if (materialNumbers.contains(order.getMaterialNumber())) {
//                order.setStatus(2L);
//                lwOrderMapper.updateLwOrder(order);
//            }
//        });
//
//        PageUtils.startPage();
//        return lwOrderList;
//    }
    public List<LwOrder> selectLwOrderList(LwOrder lwOrder)
    {
        PageUtils.clearPage();
        // 查询所有material，数量少于5000的物料
        List<LwMaterial> LwMaterialList = lwMaterialMapper.selectLwMaterialListAndquantityDemand(5000);
        PageUtils.startPage();
        List<LwOrder> LwOrderList =lwOrderMapper.selectLwOrderList(lwOrder);


        for (LwOrder order : LwOrderList) {
            order.setStatus(1L);
            lwOrderMapper.updateLwOrder(order);
        }


        // 遍历LwMaterialList和LwOrderList
        for (LwMaterial material : LwMaterialList) {
            for (LwOrder order : LwOrderList) {
                // 如果找到匹配的materialNumber
                if (material.getMaterialNumber().equals(order.getMaterialNumber())) {
                    // 设置LwOrder的status属性为2 缺货
                    order.setStatus(2L);
                    lwOrderMapper.updateLwOrder(order);
                }
            }
        }

        // 检查是否有对应的数据，如果没有，设置status为1 正常
//        for (LwOrder order : LwOrderList) {
//            if (order.getStatus() != 2) {
//                order.setStatus(1L);
//            }
//            lwOrderMapper.updateLwOrder(order);
//        }
        return LwOrderList;
    }

    /**
     * 新增原材料订单
     * 
     * @param lwOrder 原材料订单
     * @return 结果
     */
    @Override
    public int insertLwOrder(LwOrder lwOrder)
    {
        lwOrder.setQuantity(0L);
        return lwOrderMapper.insertLwOrder(lwOrder);
    }

    /**
     * 修改原材料订单
     * 
     * @param lwOrder 原材料订单
     * @return 结果
     */
    @Override
    public int updateLwOrder(LwOrder lwOrder)
    {
        return lwOrderMapper.updateLwOrder(lwOrder);
    }

    /**
     * 批量删除原材料订单
     * 
     * @param orderIds 需要删除的原材料订单主键
     * @return 结果
     */
    @Override
    public int deleteLwOrderByOrderIds(Long[] orderIds)
    {
        return lwOrderMapper.deleteLwOrderByOrderIds(orderIds);
    }

    /**
     * 删除原材料订单信息
     * 
     * @param orderId 原材料订单主键
     * @return 结果
     */
    @Override
    public int deleteLwOrderByOrderId(Long orderId)
    {
        return lwOrderMapper.deleteLwOrderByOrderId(orderId);
    }

    @Override
    public int updateOrderQuantity(LwOrder lwOrder) {

        if (lwOrder.getVariable() < 0 || lwOrder.getRemove() < 0 || lwOrder.getRemove() > lwOrder.getQuantity()){
            return -1;
        }
        LwMaterialInfo materialInfo = new LwMaterialInfo();
        LwMaterial lwMaterial = lwMaterialMapper.selectLwMaterialByMaterialNumber(lwOrder.getMaterialNumber());
        materialInfo.setMaterialId(lwMaterial.getMaterialId());
        materialInfo.setTime(new Date());
        materialInfo.setEmployeeId(SecurityUtils.getUserId());
        materialInfo.setRemark(lwOrder.getInfoRemark());

        //下单
        if (lwOrder.getVariable() > 0){
            lwOrder.setQuantity(lwOrder.getQuantity() + lwOrder.getVariable());
            materialInfo.setFlow(2L);
            materialInfo.setCompleted(lwOrder.getVariable());
        }
        //交付
        if (lwOrder.getRemove() > 0){
            lwOrder.setQuantity(lwOrder.getQuantity() - lwOrder.getRemove());
            lwOrder.setActualArrival(lwOrder.getActualArrival() + lwOrder.getRemove());
            materialInfo.setFlow(3L);
            materialInfo.setCompleted(lwOrder.getRemove());

//            LwMaterial lwMaterial = lwMaterialMapper.selectLwMaterialByMaterialNumber(lwOrder.getMaterialNumber());
//            if (lwMaterial == null){
//                LwMaterial material = new LwMaterial();
//                material.setName(lwOrder.getName());
//                material.setMaterialNumber(lwOrder.getMaterialNumber());
//                material.setModel(lwOrder.getModel());
//                material.setEncapsulation(lwOrder.getEncapsulation());
//                material.setQuantity(lwOrder.getRemove());
//                material.setRemark(lwOrder.getRemark());
//                lwMaterialMapper.insertLwMaterial(material);
//            }else {
//                lwMaterial.setQuantity(lwMaterial.getQuantity() + lwOrder.getRemove());
//                lwMaterialMapper.updateLwMaterial(lwMaterial);
//            }
        }

        lwMaterialInfoMapper.insertLwMaterialInfo(materialInfo);
        return lwOrderMapper.updateLwOrder(lwOrder);
    }

    /**
     * 订单到货移交
     */
    @Override
    public int handOverTOActualArrival(LwOrder lwOrder) {
        if (lwOrder.getRemove() < 0 || lwOrder.getRemove() > lwOrder.getActualArrival()){
            return -1;
        }
        LwMaterialInfo materialInfo = new LwMaterialInfo();
        LwMaterial lwMaterial = lwMaterialMapper.selectLwMaterialByMaterialNumber(lwOrder.getMaterialNumber());
        materialInfo.setMaterialId(lwMaterial.getMaterialId());
        materialInfo.setTime(new Date());
        materialInfo.setEmployeeId(SecurityUtils.getUserId());
        materialInfo.setRemark(lwOrder.getInfoRemark());

        if (lwOrder.getRemove() > 0) {
            lwOrder.setActualArrival(lwOrder.getActualArrival() - lwOrder.getRemove());
            materialInfo.setFlow(4L);
            materialInfo.setCompleted(lwOrder.getRemove());
        }
        lwMaterialInfoMapper.insertLwMaterialInfo(materialInfo);
        return lwOrderMapper.updateLwOrder(lwOrder);
    }

    /**
     * 导入订单数据
     *
     * @param lwOrderVoList 订单数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Transactional
    @Log(title = "excel导入", businessType = BusinessType.IMPORT)
    @Override
    public String importData(List<LwOrder> lwOrderVoList, boolean isUpdateSupport, String operName) throws Exception {
        if (StringUtils.isNull(lwOrderVoList) || lwOrderVoList.isEmpty())
        {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        List<LwOrder> existList = selectDataLwOrderList();
        for (LwOrder importData : lwOrderVoList)
        {
            try {
                // 验证是否存在
                boolean userFlag = false;
                for (LwOrder entry : existList) {
                    if (entry.getMaterialNumber().equals(importData.getMaterialNumber())) {
                        userFlag = true;
                        break;
                    }
                }
                if (!userFlag) {
                    if (importData.getQuantity() == null){
                        failureNum++;
                        failureMsg.append("<br/>").append(failureNum).append("、数据 ").append(importData.getMaterialNumber()).append(" 订货数量有误");
                        continue; // 如果数量有误，跳过当前循环
                    }
                    insertDataLwOrder(importData);
                    successNum++;
                    successMsg.append("<br/>").append(successNum).append("、数据 ").append(importData.getMaterialNumber()).append(" 导入成功");
                } else {
                    if (importData.getQuantity() == null){
                        failureNum++;
                        failureMsg.append("<br/>").append(failureNum).append("、数据 ").append(importData.getMaterialNumber()).append(" 订货数量有误");
                        continue; // 如果数量有误，跳过当前循环
                    }
                    updateDataMaterialVo(importData);
                    successNum++;
                    successMsg.append("<br/>").append(successNum).append("、数据 ").append(importData.getMaterialNumber()).append(" 更新成功");
//                } else {
//                    failureNum++;
//                    failureMsg.append("<br/>").append(failureNum).append("、数据 ").append(importData.getMaterialNumber()).append(" 已存在");
                }
            }catch (Exception e)
            {
                // 出现异常时，事务管理器会自动回滚之前的操作
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                failureNum++;
                String msg = "<br/>" + failureNum + "、物料 " + importData.getMaterialNumber() + " 导入失败：";
                failureMsg.append(msg).append(e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new Exception(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    private void updateDataMaterialVo(LwOrder importData) {
        LwOrder order = lwOrderMapper.selectLwOrderByMaterialNumber(importData.getMaterialNumber());
        order.setQuantity(order.getQuantity() + importData.getQuantity());
        order.setSupplier(importData.getSupplier());
        lwOrderMapper.updateLwOrder(order);

        LwMaterial lwMaterial = lwMaterialMapper.selectLwMaterialByMaterialNumber(order.getMaterialNumber());
        //添加下单信息
        insertLwMaterialInfo(importData,lwMaterial.getMaterialId());
    }

    private void insertDataLwOrder(LwOrder importData) {
        LwOrder order = new LwOrder();
        order.setName(importData.getName());
        order.setMaterialNumber(importData.getMaterialNumber());
        order.setModel(importData.getModel());
        order.setEncapsulation(importData.getEncapsulation());
        order.setSupplier(importData.getSupplier());
        order.setSupplier(importData.getSupplier());
        order.setQuantity(importData.getQuantity());
        lwOrderMapper.insertLwOrder(order);

        LwMaterial lwMaterial = lwMaterialMapper.selectLwMaterialByMaterialNumber(importData.getMaterialNumber());

        Long id = null;
        if (lwMaterial == null){
            LwMaterial material = new LwMaterial();
            material.setName(importData.getName());
            material.setMaterialNumber(importData.getMaterialNumber());
            material.setModel(importData.getModel());
            material.setEncapsulation(importData.getEncapsulation());
            material.setQuantity(0L);
            lwMaterialMapper.insertLwMaterial(material);

            id = lwMaterialMapper.selectLwMaterialByMaterialNumber(material.getMaterialNumber()).getMaterialId();
        }else {
            id = lwMaterial.getMaterialId();
        }
        //添加下单信息
        insertLwMaterialInfo(importData,id);
    }

    private List<LwOrder> selectDataLwOrderList() {
        return lwOrderMapper.selectDataLwOrderList();
    }

    private void insertLwMaterialInfo(LwOrder importData,Long id){
        LwMaterialInfo materialInfo = new LwMaterialInfo();
        materialInfo.setMaterialId(id);
        materialInfo.setTime(new Date());
        materialInfo.setEmployeeId(SecurityUtils.getUserId());
        materialInfo.setCompleted(importData.getQuantity());
        materialInfo.setFlow(2L);
//        String currentRemark = materialInfo.getRemark();
//        if (currentRemark == null) {
//            currentRemark = "";
//        }
        // 格式化当前时间为中文格式
        String formattedDate = sdf.format(new Date());
//        String newRemark = currentRemark + "/" + formattedDate + "_供应商:" + importData.getSupplier();
        String newRemark = formattedDate + "_供应商:" + importData.getSupplier();
        materialInfo.setRemark(newRemark);
        lwMaterialInfoMapper.insertLwMaterialInfo(materialInfo);
    }


}
